package com.guyu.plugin.oss.factory;

import com.guyu.plugin.oss.OssManager;
import com.guyu.plugin.oss.core.OssClient;
import com.guyu.plugin.oss.dao.OssDao;
import com.guyu.plugin.oss.exception.OssException;
import com.guyu.plugin.oss.properties.OssProperties;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 文件上传Factory
 */
@Slf4j
public class OssFactory {

    private static final Map<String, OssClient> CLIENT_CACHE = new ConcurrentHashMap<>();
    private static final ReentrantLock LOCK = new ReentrantLock();

    /**
     * 根据类型获取实例
     */
    public static OssClient instance(String configKey) {
        OssDao ossDao = OssManager.getOssDao();
        OssProperties properties = ossDao.get(configKey);
        if (properties == null) {
            throw new OssException("系统异常, '" + configKey + "'配置信息不存在!");
        }
        OssClient client = CLIENT_CACHE.get(configKey);
        // 客户端不存在或配置不相同则重新构建
        if (client == null || !client.checkPropertiesSame(properties)) {
            LOCK.lock();
            try {
                client = CLIENT_CACHE.get(configKey);
                if (client == null || !client.checkPropertiesSame(properties)) {
                    CLIENT_CACHE.put(configKey, new OssClient(configKey, properties));
                    log.info("创建OSS实例 key => {}", configKey);
                    return CLIENT_CACHE.get(configKey);
                }
            } finally {
                LOCK.unlock();
            }
        }
        return client;
    }


}
